﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net.Mail;
using System.Globalization;
using System.Web;
using System.Web.SessionState;

namespace OA.Common
{
    public class EMailUtil
    {
 

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="smtpServer"></param>
        /// <param name="smtpPort"></param>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        /// <param name="attachment">路径用*号隔开</param>
        /// <param name="receiver"></param>
        /// <param name="copyTo"></param>
        public static void SendEMail(string smtpServer,int smtpPort, string userName, string password, string subject, string body, string [] receiver,string[] copyTo)
        {
            try
            {
                System.Text.Encoding encoding = System.Text.Encoding.UTF8;
                System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
                msg.SubjectEncoding = encoding;//邮件标题编码               
                msg.BodyEncoding = encoding;//邮件内容编码
                msg.IsBodyHtml = true;//是否是HTML邮件
                msg.Priority = MailPriority.High;//邮件优先级
                if (copyTo != null)
                {
                    for (int i = 0; i < copyTo.Length; i++)
                    {
                        if(!copyTo[i].Equals(""))
                        msg.Bcc.Add(copyTo[i]);//设置抄送人集合
                    }
                }
                msg.From = new MailAddress(userName, userName, encoding);
                for (int i = 0; i < receiver.Length; i++)
                {
                    if (!receiver[i].Equals(""))
                    msg.To.Add(receiver[i]);
                }
                
                msg.Subject = subject;//邮件标题
                msg.Body = body.Replace("\r\n", "<br/>").Replace(" ", "&nbsp;");//邮件内容，替换字符
                
                SmtpClient client = new SmtpClient();
                client.Host = smtpServer;
                if (msg.From.Address.EndsWith("google.com") || msg.From.Address.EndsWith("gmail.com") || msg.From.Address.EndsWith("live.com"))
                {
                    client.EnableSsl = true;
                    client.Port = 587;
                }
                if (smtpPort >= 0)
                {
                    client.Port = smtpPort;
                }
                client.UseDefaultCredentials = false;
                client.Credentials = new System.Net.NetworkCredential(userName, password);
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.Send(msg);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
    }
}
